<?php
/**
 * 获取16位唯一数字字符串
 *
 * @return string 16位数字字符串
 *
 * @author zhuzhenguo
 * Modified: 2012/11/27 13:58
 */
function getUniqid() {
	$date = getdate();
	list($usec, $sec) = explode(" ", microtime());
	
	return ($date['yday'] + 200) . str_pad(($date['hours']+1) * 3600 + $date['minutes'] * 60 + $date['seconds'], 5, '0', STR_PAD_LEFT) . str_pad((int)((float)$usec * 1000000), 6, '0', STR_PAD_LEFT) . (($date['year'] - 2000) + $date['mon']);
}
/**
 * 获取自定义随机字符串
 * 
 * @param array $data (
 * bool number : 是否生成数字,
 * bool lcase : 是否生成小写字母,
 * bool ucase : 是否生成大写字母,
 * int length : 随机字符床长度 [默认: 16],
 * )
 */
function getRandom($data = array()) {
	$opt = array(
		'number' => true,
		'lcase' => true,
		'ucase' => true,
		'length' => 16
	);
	
	if ( !empty($data) ) {
		$opt = array_merge( $opt, $data );
	}
	
	$origin_data = array();
	
	$number = array( 0 => 0, 1 => 1, 2 => 2, 3 => 3, 4 => 4, 5 => 5, 6 => 6, 7 => 7, 8 => 8, 9 => 9 );
	$lcase = array( 10 => 'a', 11 => 'b', 12 => 'c', 13 => 'd', 14 => 'e', 15 => 'f', 16 => 'g', 17 => 'h', 18 => 'i', 19 => 'j', 10 => 'k', 21 => 'l', 22 => 'm', 23 => 'n', 24 => 'o', 25 => 'p', 26 => 'q', 27 => 'r', 28 => 's', 29 => 't', 30 => 'u', 31 => 'v', 32 => 'w', 33 => 'x', 34 => 'y', 35 => 'z' );
	$ucase = array( 35 => 'A', 36 => 'B', 37 => 'C', 38 => 'D', 39 => 'E', 40 => 'F', 41 => 'G', 42 => 'H', 43 => 'I', 44 => 'J', 45 => 'K', 46 => 'L', 47 => 'M', 48 => 'N', 49 => 'O', 50 => 'P', 51 => 'Q', 52 => 'R', 53 => 'S', 54 => 'T', 55 => 'U', 56 => 'V', 57 => 'W', 58 => 'X', 59 => 'Y', 60 => 'Z' );
	
	if ( $opt['number'] ) {
		if ( empty($origin_data) ) {
			$origin_data = $number;
		}
	}
	
	if ( $opt['lcase'] ) {
		if ( empty($origin_data) ) {
			$origin_data = $lcase;
		}
		else {
			$origin_data = array_merge( $origin_data, $lcase);
		}
	}
	
	if ( $opt['ucase'] ) {
		if ( empty($origin_data) ) {
			$origin_data = $ucase;
		}
		else {
			$origin_data = array_merge( $origin_data, $ucase);
		}
	}
	
	$result = '';
	for ( $i = 0; $i < $opt['length']; $i++ ) {
		$result .= $origin_data[array_rand( $origin_data, 1 )];
	}
	
	return $result;
}
/**
 * 远程获取数据
 * 
 * 注意：该函数的功能可以用curl来实现和代替。
 * $url 指定URL完整路径地址
 * @param $input_charset 编码格式。默认值：utf-8
 * @param $time_out 超时时间。默认值：60
 * return 远程输出的数据
 */
function getHttpResponse($url, $input_charset = 'utf-8', $time_out = "60") {
	$urlarr     = parse_url($url);
	$errno      = "";
	$errstr     = "";
	$transports = "";
	$responseText = "";
	if($urlarr["scheme"] == "https") {
		$transports = "ssl://";
		$urlarr["port"] = "443";
	} else {
		$transports = "tcp://";
		$urlarr["port"] = "80";
	}
	$fp=@fsockopen($transports . $urlarr['host'],$urlarr['port'],$errno,$errstr,$time_out);
	if(!$fp) {
		die("ERROR: $errno - $errstr<br />\n");
	} else {
		if (trim($input_charset) == '') {
			fputs($fp, "POST ".$urlarr["path"]." HTTP/1.1\r\n");
		}
		else {
			fputs($fp, "POST ".$urlarr["path"].'?_input_charset='.$input_charset." HTTP/1.1\r\n");
		}
		fputs($fp, "Host: ".$urlarr["host"]."\r\n");
		fputs($fp, "Content-type: application/x-www-form-urlencoded\r\n");
		fputs($fp, "Content-length: ".strlen($urlarr["query"])."\r\n");
		fputs($fp, "Connection: close\r\n\r\n");
		fputs($fp, $urlarr["query"] . "\r\n\r\n");
		while(!feof($fp)) {
			$responseText .= @fgets($fp, 1024);
		}
		fclose($fp);
		$responseText = trim(stristr($responseText,"\r\n\r\n"),"\r\n");

		return $responseText;
	}
}
/**
 * get方式获取远程数据
 * @param string $url: 路径
 * @param array $opt: curl_setopt参数
 * @return string 返回信息
 * 
 * @author zhuzhenguo
 * Modified: 2012/12/10 02:06
 */
function getHttpResponseGET($url, $opt = array()) {
	$setopt = array(
		CURLOPT_HEADER => 0,
		CURLOPT_RETURNTRANSFER => 1,
		CURLOPT_URL => $url
	);
	
	if ( !empty($opt) ) {
		$setopt = array_merge($setopt, $opt);
	}
	
	$curl = curl_init($url);
	
	foreach ($setopt as $key => $value) {
		curl_setopt($curl, $key, $value );
	}
	
	$responseText = curl_exec($curl);
	
	curl_close($curl);
	
	return $responseText;
}

/**
 * 用 curl Post 方式..
 * @author LSH 2013-02-17 
 * @param string $url                 // 目标地址
 * @param array  $opt                // curl_setopt 参数
 * @param array  $post_data     // 需要post的数据
 * @return string                        // 返回的数据..
 */
function getHttpResponsePOST($url, $opt = array(),$post_data) 
{
	$setopt = array(
			CURLOPT_HEADER => 0,                        //设置header
			CURLOPT_RETURNTRANSFER => 1,       //要求结果为字符串且输出到屏幕上
			CURLOPT_URL => $url,
			CURLOPT_POST => 1,                            //post提交方式
			CURLOPT_POSTFIELDS => $post_data, // 需要Post的数据..
	);

	if ( !empty($opt) ) {
		$setopt = array_merge($setopt, $opt);
	}

	$curl = curl_init($url);

	foreach ($setopt as $key => $value) {
		curl_setopt($curl, $key, $value );
	}

	$responseText = curl_exec($curl);

	curl_close($curl);

	return $responseText;
}
	
   
/** 构造URL 函数
 * @param array $filter:      // 选择器数组
 * @param string/array $key1:     // 特殊匹配项
 * @param string $key2:      // 待实现
 * @return string    url 参数部分 eg.  &f[relatedType]=1&f[zoneId]=350102
 * 
 * @author zhuzhenguo
 * Modified: 2012/12/20 09:55
 * 1.增加非标签情况下$key1可为数组
 */
function makeUrl($filter, $key1, $key2 = NULL) {
	$url = '';
	foreach($filter as $key => $value) 
	{
		if($key == 'tag') 
		{
			if ($key1 == 'tag' && $key2 != NULL)
			{
				foreach($value as $tag_key => $tag_value)
				{
					$url .= ($key2 == $tag_key) ? '' : '&f[tag][' . $tag_key . ']=on';
				}
			}	
			else
			{
				foreach($value as $tag_key => $tag_value) 
				{
					$url .= '&f[tag][' . $tag_key . ']=on';
				}		
			}
		}
		else
		{
			if ( is_array($key1) ) {
				$match_bool = false;
				foreach ($key1 as $key1_value) {
					if ($key == $key1_value) {
						$match_bool = true;
						break;
					}
				}
				$url .= ($match_bool) ? '' : '&f[' . $key . ']=' . urlencode($value);
			}
			else {
				$url .= ($key1 == $key) ? '' : '&f[' . $key . ']=' . urlencode($value);
			}
		}
			
	}
	return $url;
}

/**
 * 生成指定大小图片url
 *
 * @param array $data (
 * string domain: 域名,
 * string directory: 目录,
 * string filename: 文件名
 * )
 * @param int $size=50: 大小
 * @param string$type 为传入的默认图片的类型，可以是活动，圈子，电影等..
 * 
 * @return string: domain + directory + 大小 + filename
 * )
 *
 * @author zhuzhenguo
 * Modified: 2012/10/19 12:54
 *  @author LSH
 * Modified: 2012/12/19 10:03  
 *  添加了第三个参数$isSize 兼容有些图片不需要更改固定大小，例如circle 的图片
 *  Modified: 2012/12/21 10:05
 *  传入参数兼容性处理，将imageDomain 等转换为domain..  
 *  Modified: 2013/01/15 10:05
 *  添加了 cover 的处理
 *  Modified:2013/02/06 添加了默认图片的功能
 *  
 */
function createImageSizeUrl($data = array(), $size = 50,$type = null){
	
	$img_url = "";
	$arrTpl   = array('image','icon','cover'); // 可以继续补充
	
	
	// 默认图片类型..
	$_ = array();
	include(DIR_CONFIG . 'config.php');
	
	$arrTypeTpl        = $_['default_image_config'];
	
	$arrData = $data;
	foreach ($arrTpl as $sort)
	{
		foreach ($arrData as $key => $v)
		{
			if (strspn($key, $sort))
			{
				$arrData[strtolower(str_replace($sort, "", $key))] = $v;
			}
		}
	}
	
	if (empty($arrData['domain']) || empty($arrData['directory']) || empty($arrData['filename'])) 
	{
		
		if ($type != null && isset($arrTypeTpl[$type][$size]))
		{
			$default = $arrTypeTpl[$type][$size];
			$img_url = $default;
		}
		else 
		{
			// TODO:这边还需要一个 通用的默认图片...这边先用活动照片先顶着..
			$img_url = "http://image01.tbanana.com/image/".$size.'/default_activity_icon.png';
		}
		
	}
	else
	{
		if ($size == 0)
		{
			$img_url = 'http://' . $arrData['domain']. '/' . $arrData['directory'] .'/' . $arrData['filename'];
		}
		else
		{
			$img_url = 'http://' . $arrData['domain']. '/' . $arrData['directory'] .'/' . $size . '/' . $arrData['filename'];
		}
	}

	
	return $img_url;
	
}

/**
 * 中文无乱码截取字符串  -> mb_substr() 函数不能满足要求，所以需要用这个
 * @author LSH    20121218 09:34
 * @param str $sourcestr     // 需要截取的字符串
 * @param str $cutlength     // 长度
 * @return string
 */
function cut_str($sourcestr,$cutlength)
{
   $returnstr = '';
   $i = 0;
   $n = 0;
   $str_length=strlen($sourcestr);//字符串的字节数
   while (($n<$cutlength) and ($i<=$str_length))
   {
      $temp_str=substr($sourcestr,$i,1);
      $ascnum=Ord($temp_str);//得到字符串中第$i位字符的ascii码
      if ($ascnum>=224)    //如果ASCII位高与224，
      {
			$returnstr=$returnstr.substr($sourcestr,$i,3); //根据UTF-8编码规范，将3个连续的字符计为单个字符        
            $i=$i+3;            //实际Byte计为3
            $n++;            //字串长度计1
      }
      elseif ($ascnum>=192) //如果ASCII位高与192，
      {
         $returnstr=$returnstr.substr($sourcestr,$i,2); //根据UTF-8编码规范，将2个连续的字符计为单个字符
         $i=$i+2;            //实际Byte计为2
         $n++;            //字串长度计1
      }
      elseif ($ascnum>=65 && $ascnum<=90) //如果是大写字母，
      {
         $returnstr=$returnstr.substr($sourcestr,$i,1);
         $i=$i+1;            //实际的Byte数仍计1个
         $n++;            //但考虑整体美观，大写字母计成一个高位字符
      }
      else                //其他情况下，包括小写字母和半角标点符号，
      {
         $returnstr=$returnstr.substr($sourcestr,$i,1);
         $i=$i+1;            //实际的Byte数计1个
         $n=$n+0.5;        //小写字母和半角标点等与半个高位字符宽...
      }
   }
         if ($str_length>$i){
          $returnstr = $returnstr . "...";//超过长度时在尾处加上省略号
      }
    return $returnstr;
}

/**
 * 判断是否拥有此权限
 * @author LSH   2012-12-26 09:13
 * @param INT $sourceMask  // 全部权限掩码
 * @param INT $subMask       // 单个权限掩码
 * @return boolean TRUR 存在 ; FALSE 不存在
 */
function judgeAccess($sourceMask,$subMask)
{
	return !!((+$sourceMask)&(+$subMask));
}

/**
 *  取消此权限
 * @author LSH   2012-12-26 09:13
 * @param INT $sourceMask    // 全部权限掩码
 * @param INT $subMask         // 单个权限掩码
 * @return 权限 掩码
 */
function unsetAccess($sourceMask,$subMask)
{
	return (+$sourceMask)&~(+$subMask);
}

/**
 *  添加此权限
 * @author LSH   2012-12-26 09:13
 * @param INT $sourceMask   // 全部权限掩码
 * @param INT $subMask        // 单个权限掩码
 * @return 权限 掩码
 */
function setAccess($sourceMask,$subMask)
{
	return (+$sourceMask)|(+$subMask);
}

/**
 * 获取时间差字符串 -- 主要用在 微博 发表时间上的..
 * @author  LSH 2013-01-16 09:59
 * @param INT $time   // 发表的时间
 * @param INT $now   // 当前时间   不传自动获取
 * @return string
 */
function getTimeStr($time,$now = null)
{
	$timeStr = "";
	if ($now == null)
	{
		$now = time();
	}
	if (($now - $time) > 60*60*24*30 *12)
	{
		$timeStr =ceil( ($now - $time) / (60*60*24 *24*12)).'年前';
	}
	elseif (($now - $time) > 60*60*24*30 && ($now - $time) < 60*60*24*30 *12)
	{
		$timeStr = ceil( ($now - $time) / (60*60*24*30)).'月前';
	}
	elseif (($now - $time) > 60*60*24*7 && ($now - $time) < 60*60*24*30)
	{
		$timeStr = ceil(($now - $time) / (60*60*24*7)).'周前';
	}	
	elseif (($now - $time) > 60*60*24 && ($now - $time) < 60*60*24*7)
	{
		$timeStr = ceil(($now - $time) / (60*60*24)).'天前';
	}
	elseif (($now - $time) < 60*60*24 && ($now - $time) > 60*60)
	{
		$timeStr = ceil(($now - $time) / (60*60)).'小时前';
	}
	elseif (($now - $time) < 60*60 && ($now - $time) > 60)
	{
		$timeStr = ceil(($now - $time) / (60)).'分前';
	}
	else
	{
		$timeStr = ceil($now - $time) .'秒前';
	}
	
	return $timeStr;
}
/**
 * 替换内容中的表情
 * @author  HMJ 2013-02-05 09:27
 */
function ubb_replace($data){
	if (false !== strpos($data, '[')) {
		if (preg_match_all('~\[(.+?)\]~', $data, $match)) {
			static $face_conf=null;
			if(!$face_conf) {
				$filename = 'face';
				$file = DIR_CONFIG . $filename . '.php';
				if (file_exists($file)) {
					$_ = array();
					include($file);
					$face_conf = $_['face'];
				} else {
					trigger_error('Error: Could not load config ' . $filename . '!');
					exit();
				}
			}
			foreach ($match[0] as $k => $v) {
				if (false != @($img_src = $face_conf[$match[1][$k]]['url']))
					$data = str_replace($v, '<img src="'.$img_src.'" border="0"/>', $data);
			}
		}
	}

	return $data;
}
?>